package com.ruibang.glass.purchase.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.DictInfo;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceCreate;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceStatus;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.common.domain.material.MaterialALLOutboundManagement;
import com.ruibang.glass.common.domain.material.MaterialAllManagementInventory;
import com.ruibang.glass.common.domain.material.MaterialAllOutboundItem;
import com.ruibang.glass.common.domain.material.MaterialManagement;
import com.ruibang.glass.frequencycontrol.annotation.RedissonLock;
import com.ruibang.glass.purchase.constant.Constants;
import com.ruibang.glass.purchase.constant.PurchaseErrorCode;
import com.ruibang.glass.purchase.constant.PurchaseMenuIdCode;
import com.ruibang.glass.purchase.constant.PurchaseUseMaterialCode;
import com.ruibang.glass.purchase.domain.req.MaterialInventoryItem;
import com.ruibang.glass.purchase.domain.req.PurchaseReturnReq;
import com.ruibang.glass.purchase.entity.*;
import com.ruibang.glass.purchase.feign.CamundaApi;
import com.ruibang.glass.purchase.feign.FileApi;
import com.ruibang.glass.purchase.feign.MaterialApi;
import com.ruibang.glass.purchase.feign.PortalApi;
import com.ruibang.glass.purchase.mapper.*;
import com.ruibang.glass.purchase.service.*;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.constant.CommonConstant;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruibang.glass.common.constants.Constants.FINISH_NODE_KEY;
import static com.ruibang.glass.common.constants.RedisKey.*;

/**
 * <p>
 * 采购退货表，用于记录采购退货的相关信息 服务实现类
 * </p>
 *
 * @author mameng
 * @since 2024-03-28
 */
@Service
public class PurchaseReturnsServiceImpl extends ServiceImpl<PurchaseReturnsMapper, PurchaseReturns> implements PurchaseReturnsService {


    @Autowired
    private PurchaseReturnGoodsMapper purchaseReturnGoodsMapper;

    @Autowired
    private PurchaseOrderDetailsService purchaseOrderDetailsService;

    @Autowired
    private PurchaseRelatedProductMapper purchaseRelatedProductMapper;

    @Autowired
    private PurchaseArrivalProductService purchaseArrivalProductService;

    @Autowired
    private PurchaseArrivalOrdersMapper purchaseArrivalOrdersMapper;


    @Autowired
    private MaterialApi materialApi;

    @Autowired
    private RedisSingleService redisService;

    @Autowired
    private PortalApi portalApi;

    private static final String PURCHASE_IN_NUMBER = "purchase_in_number";

    @Autowired
    private CommonService commonService;

    @Autowired
    private FileApi fileApi;

    @Autowired
    private CamundaApi camundaApi;

    @Autowired
    private TransactionTemplate transactionTemplate;


    @Override
    public IPage<PurchaseReturns> getPage(PurchaseReturnReq purchaseReturnReq) {
        LambdaQueryWrapper<PurchaseReturns> queryWrapper = Wrappers.<PurchaseReturns>lambdaQuery();
        if (StringUtils.isNotEmpty(purchaseReturnReq.getReturnOrderNumber())) {
            queryWrapper.like(PurchaseReturns::getReturnOrderNumber, purchaseReturnReq.getReturnOrderNumber());
        }
        if (StringUtils.isNotEmpty(purchaseReturnReq.getPurchaseOrderNumber())) {
            queryWrapper.like(PurchaseReturns::getPurchaseOrderNumber, purchaseReturnReq.getPurchaseOrderNumber());
        }
        if (StringUtils.isNotEmpty(purchaseReturnReq.getReturnType())) {
            queryWrapper.eq(PurchaseReturns::getReturnType, purchaseReturnReq.getReturnType());
        }
        Page<PurchaseReturns> purchaseArrivalOrdersPage = baseMapper.selectPage(new Page<PurchaseReturns>(purchaseReturnReq.getPageNo(), purchaseReturnReq.getPageSize()),
                queryWrapper.orderByDesc(PurchaseReturns::getReturnOrderNumber)
        );
        Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
        List<String> businessKeys = purchaseArrivalOrdersPage.getRecords().stream().map(PurchaseReturns::getId).collect(Collectors.toList());
        Map<String, BpmProcessInstanceStatus> processMap = null;
        //获取业务流程状态
        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(businessKeys);
        if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
            processMap = resultBody.getData().stream().collect(Collectors.toMap(bp -> bp.getBusinessKey(), bp -> bp, (bp1, bp2) -> bp1));
        }
        for (PurchaseReturns purchaseReturns : purchaseArrivalOrdersPage.getRecords()) {
            if (processMap != null && processMap.get(purchaseReturns.getId()) != null) {
                BpmProcessInstanceStatus process = processMap.get(purchaseReturns.getId());
                purchaseReturns.setProcessId(process.getProcessInstanceId());
                purchaseReturns.setNodeName(process.getNodeName());
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(process.getUserId())) {
                    if (process.getUserId().indexOf(CommonConstant.SpecialSign.COMMA.getName()) != -1) {
                        String[] userIds = process.getUserId().split(CommonConstant.SpecialSign.COMMA.getName());
                        StringBuilder userName = new StringBuilder();
                        int size = userIds.length;
                        for (int i = 0; i < size; i++) {
                            String name = userMap.get(userIds[i]) == null ? "" : userMap.get(userIds[i]).toString();
                            if (i == size - 1) {
                                userName.append(name);
                            } else {
                                userName.append(name).append(CommonConstant.SpecialSign.COMMA.getName());
                            }
                        }
                        purchaseReturns.setApproveUserId(process.getUserId());
                        purchaseReturns.setApproveUser(userName.toString());
                    } else {
                        purchaseReturns.setApproveUserId(process.getUserId());
                        purchaseReturns.setApproveUser(userMap.get(process.getUserId()) == null ? "" : userMap.get(process.getUserId()).toString());
                    }
                }
            }
        }
        return purchaseArrivalOrdersPage;
    }

    /**
     * 退货新增到库存表
     *
     * @param purchaseReturns
     */
    @Override
    public void addPurchaseReturns(PurchaseReturns purchaseReturns) {
        //校验
        if (CollectionUtils.isEmpty(purchaseReturns.getPurchaseReturnGoodsList())) {
            throw new ServiceException(PurchaseErrorCode.RETURN_ORDER_ITEM_IS_EMPTY.getCode(), PurchaseErrorCode.RETURN_ORDER_ITEM_IS_EMPTY.getMsg());
        }
        for (PurchaseReturnGoods purchaseReturnGoods : purchaseReturns.getPurchaseReturnGoodsList()) {
            if (StringUtils.equals(purchaseReturnGoods.getWarehouseCode(), PurchaseUseMaterialCode.YCLK_CK)) {
                if (StringUtils.isEmpty(purchaseReturnGoods.getPcNumber())) {
                    throw new ServiceException(PurchaseErrorCode.RETURN_NO_PC_ITEM_IS_EMPTY.getCode(), PurchaseErrorCode.RETURN_NO_PC_ITEM_IS_EMPTY.getMsg());
                }
                if (StringUtils.isEmpty(purchaseReturnGoods.getBarcodeNumber())) {
                    throw new ServiceException(PurchaseErrorCode.RETURN_NO_BARCODE_ITEM_IS_EMPTY.getCode(), PurchaseErrorCode.RETURN_NO_BARCODE_ITEM_IS_EMPTY.getMsg());
                }
            }
        }


        String execute = transactionTemplate.execute(tran -> {
            baseMapper.insert(purchaseReturns);
            BigDecimal bigDecimal = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(purchaseReturns.getPurchaseReturnGoodsList())) {
                for (PurchaseReturnGoods purchaseReturnGoods : purchaseReturns.getPurchaseReturnGoodsList()) {
                    //更具到货单号和物料code 获取初始那条数据
                    if (purchaseReturnGoods.getQuantity() != null && purchaseReturnGoods.getTaxInclusiveUnitPrice() != null) {
                        BigDecimal multiply = purchaseReturnGoods.getQuantity().multiply(purchaseReturnGoods.getTaxInclusiveUnitPrice());
                        bigDecimal = bigDecimal.add(multiply);
                    }
                    if (purchaseReturnGoods.getQuantity() == null) {
                        throw new ServiceException(PurchaseErrorCode.NO_RETURN_PRODUCTS_NO_QUALITY.getCode(), PurchaseErrorCode.NO_RETURN_PRODUCTS_NO_QUALITY.getMsg());

                    }
                    if (purchaseReturnGoods.getQuantity().compareTo(purchaseReturnGoods.getArrivalQuantity()) > 0) {
                        throw new ServiceException(PurchaseErrorCode.QUALITY_IS_MORE_ALL_REQUEST.getCode(), PurchaseErrorCode.QUALITY_IS_MORE_ALL_REQUEST.getMsg());
                    } else {
                        List<PurchaseArrivalOrders> purchaseArrivalOrders = purchaseArrivalOrdersMapper.selectList(Wrappers.<PurchaseArrivalOrders>lambdaQuery().select(PurchaseArrivalOrders::getId)
                                .eq(PurchaseArrivalOrders::getPurchaseOrderNumber, purchaseReturns.getPurchaseOrderNumber())
                        );
                        List<String> collect = purchaseArrivalOrders.stream().map(PurchaseArrivalOrders::getId).distinct().collect(Collectors.toList());
                        PurchaseArrivalProduct purchaseArrivalProduct = purchaseArrivalProductService.
                                getOne(Wrappers.<PurchaseArrivalProduct>lambdaQuery().in(PurchaseArrivalProduct::getSaleArrivalId
                                        , collect)
                                        .eq(PurchaseArrivalProduct::getItemCode, purchaseReturnGoods.getItemCode())
                                        .orderByAsc(PurchaseArrivalProduct::getCreateTime)
                                        .last("limit 1")
                                );
                        if (purchaseArrivalProduct.getForzenQuantity() != null) {
                            Integer add = purchaseArrivalProduct.getForzenQuantity() + purchaseReturnGoods.getQuantity().intValue();
                            purchaseArrivalProduct.setForzenQuantity(add);
                        } else {
                            purchaseArrivalProduct.setForzenQuantity(purchaseReturnGoods.getQuantity().intValue());
                        }

                        purchaseReturnGoods.setInventoryNumber(purchaseArrivalProduct.getInventoryNumber());
                        purchaseReturnGoods.setInventoryId(purchaseArrivalProduct.getInventoryId());
                        purchaseArrivalProductService.updateById(purchaseArrivalProduct);
                    }

                    purchaseReturnGoods.setReturnId(purchaseReturns.getId());
                    purchaseReturnGoodsMapper.insert(purchaseReturnGoods);
                }
            }
            purchaseReturns.setReturnAllAmount(bigDecimal);
            if (CollectionUtils.isNotEmpty(purchaseReturns.getFileList())) {
                FileBusiness fileBusiness = new FileBusiness();
                fileBusiness.setFileIds(purchaseReturns.getFileList());
                fileBusiness.setBusinessId(purchaseReturns.getId());
                fileApi.updateBusinessById(fileBusiness);
            }
            purchaseReturns.setApproveStatus(Constants.ZERO_STR);
            purchaseReturns.setReturnChangeStatus(Constants.ZERO_STR);
            baseMapper.updateById(purchaseReturns);
            return Constants.ONE_STR;
        });
        if (StringUtils.equals(execute, Constants.ONE_STR)) {
            BpmProcessInstanceCreate instanceCreate = new BpmProcessInstanceCreate();
            instanceCreate.setBusinessKey(purchaseReturns.getId());
            instanceCreate.setMenuId(purchaseReturns.getMenuId());
            //发起流程
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(purchaseReturns.getApplyId())) {
                Map<String, Object> variables = new HashMap<>();
                variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_STARTER_USER_ID, purchaseReturns.getApplyId());
                variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_BUSINESS_KEY, purchaseReturns.getId());
                variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_MENU_ID, purchaseReturns.getMenuId());
                instanceCreate.setVariables(variables);
            }
            commonService.startProcess(instanceCreate);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePurchaseReturns(PurchaseReturns purchaseReturns) {
        if (CollectionUtils.isEmpty(purchaseReturns.getPurchaseReturnGoodsList())) {
            throw new ServiceException(PurchaseErrorCode.NO_RETURN_PRODUCTS.getCode(), PurchaseErrorCode.NO_RETURN_PRODUCTS.getMsg());
        }

        for (PurchaseReturnGoods purchaseReturnGoods : purchaseReturns.getPurchaseReturnGoodsList()) {
            if (StringUtils.equals(purchaseReturnGoods.getWarehouseCode(), PurchaseUseMaterialCode.YCLK_CK)) {
                if (StringUtils.isEmpty(purchaseReturnGoods.getPcNumber())) {
                    throw new ServiceException(PurchaseErrorCode.RETURN_NO_PC_ITEM_IS_EMPTY.getCode(), PurchaseErrorCode.RETURN_NO_PC_ITEM_IS_EMPTY.getMsg());
                }
                if (StringUtils.isEmpty(purchaseReturnGoods.getBarcodeNumber())) {
                    throw new ServiceException(PurchaseErrorCode.RETURN_NO_BARCODE_ITEM_IS_EMPTY.getCode(), PurchaseErrorCode.RETURN_NO_BARCODE_ITEM_IS_EMPTY.getMsg());
                }
            }
        }

        fileApi.deleteByBusinessId(purchaseReturns.getId());
        //冻结数量回退
        List<PurchaseReturnGoods> purchaseReturnGoods1 = purchaseReturnGoodsMapper.selectList(Wrappers.<PurchaseReturnGoods>lambdaQuery().eq(PurchaseReturnGoods::getReturnId, purchaseReturns.getId()));

        for (PurchaseReturnGoods purchaseReturnGoods : purchaseReturnGoods1) {
            List<PurchaseArrivalOrders> purchaseArrivalOrders = purchaseArrivalOrdersMapper.selectList(Wrappers.<PurchaseArrivalOrders>lambdaQuery().select(PurchaseArrivalOrders::getId)
                    .eq(PurchaseArrivalOrders::getPurchaseOrderNumber, purchaseReturns.getPurchaseOrderNumber())
            );
            List<String> collect = purchaseArrivalOrders.stream().map(PurchaseArrivalOrders::getId).distinct().collect(Collectors.toList());
            PurchaseArrivalProduct purchaseArrivalProduct = purchaseArrivalProductService.
                    getOne(Wrappers.<PurchaseArrivalProduct>lambdaQuery().in(PurchaseArrivalProduct::getSaleArrivalId
                            , collect)
                            .eq(PurchaseArrivalProduct::getItemCode, purchaseReturnGoods.getItemCode())
                            .gt(PurchaseArrivalProduct::getForzenQuantity, Constants.ZERO_INT)
                            .last("limit 1")
                    );
            if (purchaseArrivalProduct.getForzenQuantity() != null) {
                Integer count = purchaseArrivalProduct.getForzenQuantity() - purchaseReturnGoods.getQuantity().intValue();
                purchaseArrivalProduct.setForzenQuantity(count);
                purchaseArrivalProductService.updateById(purchaseArrivalProduct);
            }

        }

        purchaseReturnGoodsMapper.delete(Wrappers.<PurchaseReturnGoods>lambdaQuery().eq(PurchaseReturnGoods::getReturnId, purchaseReturns.getId()));
        BigDecimal bigDecimal = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(purchaseReturns.getPurchaseReturnGoodsList())) {
            for (PurchaseReturnGoods purchaseReturnGoods : purchaseReturns.getPurchaseReturnGoodsList()) {

                if (purchaseReturnGoods.getQuantity() != null && purchaseReturnGoods.getTaxInclusiveUnitPrice() != null) {
                    BigDecimal multiply = purchaseReturnGoods.getQuantity().multiply(purchaseReturnGoods.getTaxInclusiveUnitPrice());
                    bigDecimal = bigDecimal.add(multiply);
                }

                //更具到货单号和物料code 获取初始那条数据
                List<PurchaseArrivalOrders> purchaseArrivalOrders = purchaseArrivalOrdersMapper.selectList(Wrappers.<PurchaseArrivalOrders>lambdaQuery().select(PurchaseArrivalOrders::getId)
                        .eq(PurchaseArrivalOrders::getPurchaseOrderNumber, purchaseReturns.getPurchaseOrderNumber())
                );
                List<String> collect = purchaseArrivalOrders.stream().map(PurchaseArrivalOrders::getId).distinct().collect(Collectors.toList());

                PurchaseArrivalProduct purchaseArrivalProduct = purchaseArrivalProductService.
                        getOne(Wrappers.<PurchaseArrivalProduct>lambdaQuery().in(PurchaseArrivalProduct::getSaleArrivalId
                                , collect)
                                .eq(PurchaseArrivalProduct::getItemCode, purchaseReturnGoods.getItemCode())
                                .orderByAsc(PurchaseArrivalProduct::getCreateTime)
                                .last("limit 1")
                        );
                if (purchaseArrivalProduct.getForzenQuantity() != null) {
                    Integer add = purchaseArrivalProduct.getForzenQuantity() + purchaseReturnGoods.getQuantity().intValue();
                    purchaseArrivalProduct.setForzenQuantity(add);
                }
                purchaseReturnGoods.setInventoryNumber(purchaseArrivalProduct.getInventoryNumber());
                purchaseReturnGoods.setInventoryId(purchaseArrivalProduct.getInventoryId());
                purchaseArrivalProductService.updateById(purchaseArrivalProduct);
                purchaseReturnGoods.setReturnId(purchaseReturns.getId());
                purchaseReturnGoodsMapper.insert(purchaseReturnGoods);

            }
        }
        if (StringUtils.isEmpty(purchaseReturns.getReturnChangeStatus())) {
            purchaseReturns.setReturnChangeStatus(Constants.ZERO_STR);
        }
        //重新冻结新的数量
        PurchaseReturns purchaseReturns1 = baseMapper.selectById(purchaseReturns.getId());
        purchaseReturns.setReturnAllAmount(bigDecimal);
        purchaseReturns.setApproveStatus(purchaseReturns1.getApproveStatus());
        purchaseReturns.setReturnChangeStatus(Constants.ZERO_STR);
        baseMapper.updateById(purchaseReturns);
        if (CollectionUtils.isNotEmpty(purchaseReturns.getFileList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setFileIds(purchaseReturns.getFileList());
            fileBusiness.setBusinessId(purchaseReturns.getId());
            fileApi.updateBusinessById(fileBusiness);
        }
    }

    @Override
    public String getTHNumber() {
        return getMaterialTHNumber();
    }


    @RedissonLock(key = PURCHASE_TH_WAREHOUSE_NUMBER, prefixKey = "lock_")
    public String getMaterialTHNumber() {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT_UN_SEPARATE));
        date = "TH".concat(date);
        String code = "";
        Serializable number = redisService.get(PURCHASE_TH_WAREHOUSE_NUMBER);
        if (number == null || StringUtils.isBlank(number.toString())) {
            ResultBody<String> resultBody = portalApi.getValueByCode(PURCHASE_TH_WAREHOUSE_NUMBER);
            if (resultBody != null && StringUtils.isNotBlank(resultBody.getData())) {
                number = resultBody.getData();
            }
        }
        if (number != null && StringUtils.isNotBlank(number.toString()) && number.toString().length() > 10) {
            String sequenceStr = number.toString().substring(10);
            int sequenceInt = Integer.parseInt(sequenceStr);
            sequenceInt = sequenceInt + 1;
            String newSequence = String.valueOf(sequenceInt);
            if (newSequence.length() == CommonConstant.FIVE_INT) {
                code = date.concat("0001");
            } else {
                code = date.concat(String.format("%04d", sequenceInt)); // 格式化数字为4位，不足部分用0填充
            }
        } else {
            code = date.concat("0001");
        }
        redisService.set(PURCHASE_TH_WAREHOUSE_NUMBER, code);
        DictInfo info = new DictInfo();
        info.setCsdm(PURCHASE_TH_WAREHOUSE_NUMBER);
        info.setCsmc(code);
        portalApi.updateValueByCode(info);
        return code;
    }


    @Override
    public void processNotice(String businessId) {
        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(Arrays.asList(businessId));
        PurchaseReturns purchaseReturns2 = baseMapper.selectById(businessId);
        if (purchaseReturns2 != null) {

            if (purchaseReturns2.getApproveStatus().equals(Constants.TWO_STR)) {
                PurchaseReturns purchaseReturns = baseMapper.selectById(businessId);
                List<PurchaseReturnGoods> purchaseReturnGoods = purchaseReturnGoodsMapper.selectList(Wrappers.<PurchaseReturnGoods>lambdaQuery().eq(PurchaseReturnGoods::getReturnId, purchaseReturns.getId()));
                Map<String, List<PurchaseReturnGoods>> collect = purchaseReturnGoods.stream().collect(Collectors.groupingBy(PurchaseReturnGoods::getWarehouseCode));
                if (collect != null) {
                    for (String wareHouseCode : collect.keySet()) {
                        MaterialALLOutboundManagement materialALLOutboundManagement = new MaterialALLOutboundManagement();
                        materialALLOutboundManagement.setOutNumber(getMaterialOUTNumber());
                        materialALLOutboundManagement.setType(Constants.THREE_STR);
                        materialALLOutboundManagement.setUsePerson(purchaseReturns.getApplyName());
                        materialALLOutboundManagement.setUsePersonId(purchaseReturns.getApplyId());
                        materialALLOutboundManagement.setWarehouseCode(wareHouseCode);
                        materialALLOutboundManagement.setPreparer(purchaseReturns.getApplyName());
                        materialALLOutboundManagement.setPreparerId(purchaseReturns.getApplyId());
                        materialALLOutboundManagement.setUseReason("main_pl_purpose_cgth");
                        List<MaterialAllOutboundItem> materialAllOutboundItemList = new ArrayList<>();
                        for (PurchaseReturnGoods purchaseReturnGoods1 : collect.get(wareHouseCode)) {
                            PurchaseReturns purchaseReturns1 = baseMapper.getPurchaseReturns(purchaseReturnGoods1.getInventoryNumber(), purchaseReturnGoods1.getItemCode());

                            MaterialAllOutboundItem materialAllOutboundItem = new MaterialAllOutboundItem();
                            materialAllOutboundItem.setItemCode(purchaseReturnGoods1.getItemCode());
                            materialAllOutboundItem.setItemName(purchaseReturnGoods1.getItemName());
                            materialAllOutboundItem.setItemId(purchaseReturnGoods1.getItemId());
                            materialAllOutboundItem.setQuantity(purchaseReturnGoods1.getQuantity());
                            materialAllOutboundItem.setUnit(purchaseReturnGoods1.getUnit());
                            materialAllOutboundItem.setSpecification(purchaseReturnGoods1.getSpecificationModel());
                            materialAllOutboundItem.setBatchNumber(purchaseReturnGoods1.getPcNumber());
                            materialAllOutboundItem.setReturnId(purchaseReturnGoods1.getId());
                            materialAllOutboundItem.setSupplierName(purchaseReturns.getSupplierName());
                            materialAllOutboundItem.setSupplierId(purchaseReturns.getSupplierId());
                            materialAllOutboundItem.setWarehouseCode(purchaseReturnGoods1.getWarehouseCode());
                            materialAllOutboundItem.setBarcodeNumber(purchaseReturnGoods1.getBarcodeNumber());
                            materialAllOutboundItem.setBatchNumber(purchaseReturnGoods1.getPcNumber());
                            if (purchaseReturns1 != null) {
                                materialAllOutboundItem.setWarehouseName(purchaseReturns1.getWarehouseName());
                                materialALLOutboundManagement.setWarehouseName(purchaseReturns1.getWarehouseName());
                                materialAllOutboundItem.setStorageLocationId(purchaseReturns1.getLocationId());
                                materialAllOutboundItem.setStorageLocationName(purchaseReturns1.getLocationName());
                                String wareId = baseMapper.GetWareId(purchaseReturns1.getWarehouseName());
                                materialALLOutboundManagement.setWarehouseId(wareId);
                                materialAllOutboundItem.setWarehouseId(wareId);
                            }
                            materialAllOutboundItemList.add(materialAllOutboundItem);
                        }
                        materialALLOutboundManagement.setMaterialAllOutboundItemList(materialAllOutboundItemList);
                        if (wareHouseCode.equals(PurchaseUseMaterialCode.YCLK_CK)) {

                            materialALLOutboundManagement.setMenuId(PurchaseMenuIdCode.MENU_ID_YCL_OUT.getMsg());
                            materialApi.outYClMaterial(materialALLOutboundManagement);
                        } else {
                            materialALLOutboundManagement.setMenuId(PurchaseMenuIdCode.MENU_ID_All_OUT.getMsg());
                            materialApi.outAllMaterial(materialALLOutboundManagement);
                        }
                    }
                }
            }
        }
    }

    @Override
    public PurchaseReturns getPurchaseReturnsById(String id) {
        PurchaseReturns purchaseReturns = baseMapper.selectById(id);
        List<PurchaseReturnGoods> list = purchaseReturnGoodsMapper.selectList(Wrappers.<PurchaseReturnGoods>lambdaQuery().eq(PurchaseReturnGoods::getReturnId, id));
        ResultBody<List<String>> fileIdsByBusinessId = fileApi.getFileIdsByBusinessId(id);
        if (fileIdsByBusinessId != null) {
            purchaseReturns.setFileList(fileIdsByBusinessId.getData());
        }
        purchaseReturns.setPurchaseReturnGoodsList(list);
        return purchaseReturns;
    }

    @Override
    public void updateOrderQuality(List<String> ids) {
        List<PurchaseReturnGoods> purchaseReturnGoods = purchaseReturnGoodsMapper.selectBatchIds(ids);
        Map<String, List<PurchaseReturnGoods>> collect = purchaseReturnGoods.stream().collect(Collectors.groupingBy(PurchaseReturnGoods::getReturnId));
        for (String returnId : collect.keySet()) {
            PurchaseReturns purchaseReturns = baseMapper.selectById(returnId);
            purchaseReturns.setReturnChangeStatus(Constants.ONE_STR);
            baseMapper.updateById(purchaseReturns);
            for (PurchaseReturnGoods purchaseReturnGoods1 : collect.get(returnId)) {
                PurchaseOrderDetails one = purchaseOrderDetailsService.getOne(Wrappers.<PurchaseOrderDetails>lambdaQuery().eq(PurchaseOrderDetails::getPurchaseOrderNumber, purchaseReturns.getPurchaseOrderNumber()));
                if (purchaseReturnGoods1.getWarehouseCode().equals(PurchaseUseMaterialCode.YCLK_CK)) {
                    PurchaseRelatedProduct purchaseRelatedProduct = purchaseRelatedProductMapper.selectOne(Wrappers.<PurchaseRelatedProduct>lambdaQuery()
                            .eq(PurchaseRelatedProduct::getDetailId, one.getId())
                            .eq(PurchaseRelatedProduct::getItemCode, purchaseReturnGoods1.getItemCode())
                            .last("limit 1")
                    );
                    if (purchaseRelatedProduct != null) {
                        if (purchaseRelatedProduct.getQuantity() != null) {
                            BigDecimal add = BigDecimal.valueOf(purchaseRelatedProduct.getQuantity()).add(purchaseReturnGoods1.getQuantity());
                            purchaseRelatedProduct.setQuantity(add.doubleValue());
                        } else {
                            purchaseRelatedProduct.setQuantity(purchaseReturnGoods1.getQuantity().doubleValue());
                        }
                        purchaseRelatedProductMapper.updateById(purchaseRelatedProduct);
                    }
                } else {
                    PurchaseRelatedProduct purchaseRelatedProduct = purchaseRelatedProductMapper.selectOne(Wrappers.<PurchaseRelatedProduct>lambdaQuery()
                            .eq(PurchaseRelatedProduct::getDetailId, one.getId())
                            .eq(PurchaseRelatedProduct::getItemCode, purchaseReturnGoods1.getItemCode())
                            .last("limit 1")
                    );
                    if (purchaseRelatedProduct != null) {
                        if (purchaseRelatedProduct.getQuantity() != null) {
                            BigDecimal add = BigDecimal.valueOf(purchaseRelatedProduct.getQuantity()).add(purchaseReturnGoods1.getQuantity());
                            purchaseRelatedProduct.setQuantity(add.doubleValue());
                        } else {
                            purchaseRelatedProduct.setQuantity(purchaseReturnGoods1.getQuantity().doubleValue());
                        }
                        purchaseRelatedProductMapper.updateById(purchaseRelatedProduct);
                    }
                }
            }

        }
    }


    @RedissonLock(key = MATERIAL_OUT_WAREHOUSE_NUMBER, prefixKey = "lock_")
    public String getMaterialOUTNumber() {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT_UN_SEPARATE));
        date = "OUT".concat(date);
        String code = "";

        Serializable number = redisService.get(MATERIAL_OUT_WAREHOUSE_NUMBER);
        if (number == null || StringUtils.isBlank(number.toString())) {
            ResultBody<String> resultBody = portalApi.getValueByCode(MATERIAL_OUT_WAREHOUSE_NUMBER);
            if (resultBody != null && StringUtils.isNotBlank(resultBody.getData())) {
                number = resultBody.getData();
            }
        }
        if (number != null && StringUtils.isNotBlank(number.toString()) && number.toString().length() > 11) {
            String sequenceStr = number.toString().substring(11);
            int sequenceInt = Integer.parseInt(sequenceStr);
            sequenceInt = sequenceInt + 1;
            String newSequence = String.valueOf(sequenceInt);
            if (newSequence.length() == CommonConstant.FIVE_INT) {
                code = date.concat("0001");
            } else {
                code = date.concat(String.format("%04d", sequenceInt)); // 格式化数字为4位，不足部分用0填充
            }
        } else {
            code = date.concat("0001");
        }
        redisService.set(MATERIAL_OUT_WAREHOUSE_NUMBER, code);
        DictInfo info = new DictInfo();
        info.setCsdm(MATERIAL_OUT_WAREHOUSE_NUMBER);
        info.setCsmc(code);
        portalApi.updateValueByCode(info);
        return code;
    }


}
